package com.yidian.controller.business;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yidian.pojo.goods.Goods;
import com.yidian.pojo.goods.Sku;
import com.yidian.pojo.goods.Spu;
import com.yidian.server.goods.CategoryService;
import com.yidian.server.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whb
 * @create 2021-06-18 15:32
 * @desciption 商品详细页静态渲染控制类
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    @Reference
    private SpuService spuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private TemplateEngine templateEngine; //注入thymeleaf模板引擎
    @Value("${pagePath}")
    private String pagePath;

    /**
     * 生成商品详细页
     *
     * @param spuId
     */
    @GetMapping("/detailPage")
    public void createDetailPage(String spuId) {
        //根据spuId查询商品信息
        Goods goods = spuService.findGoodsById(spuId);
        //获取Spu信息
        Spu spu = goods.getSpu();
        //获取Sku列表
        List<Sku> skuList = goods.getSkuList();
        //查询商品三级分类信息
        List<String> categoryList = new ArrayList<>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());
        //查询spu参数列表
        Map<String, Object> spuParamItems = JSON.parseObject(spu.getParaItems());
        //查询spu规格列表
        Map<String, Object> spuSpecItems = JSON.parseObject(spu.getSpecItems());

        //sku详细页面地址列表（sku的spec字符串为key，sku详细页面地址为value）
        Map<String, Object> skuUrlMap = new HashMap<>();
        for (Sku sku : skuList) {
            if ("1".equals(sku.getStatus())) {
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                skuUrlMap.put(specJson, sku.getId() + ".html");
            }
        }

        //使用原生的thymeleaf生成页面（每个sku生成一个页面）
        for (Sku sku : skuList) {
            //1.创建上下文
            Context context = new Context();
            HashMap<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            dataModel.put("spuImages", spu.getImages().split(","));
            dataModel.put("skuImages", sku.getImages().split(","));
            dataModel.put("categoryList", categoryList);//商品三级分类信息，满足商品详细页面包屑导航
            dataModel.put("spuParamItems", spuParamItems);
            Map<String, Object> skuSpecItems = JSON.parseObject(sku.getSpec());//查询sku规格
            dataModel.put("skuSpecItems", skuSpecItems);
            dataModel.put("spuSpecItems", spuSpecItems);

            //{"颜色":["天空之境","珠光贝母"],"内存":["8GB+64GB","8GB+128GB","8GB+256GB"]}
            //{"颜色":[{ 'option':'天空之境',checked:true },{ 'option':'珠光贝母',checked:false }],.....}
            Map<String, Object> specMap = JSON.parseObject(spu.getSpecItems());//规格和规格选项
            for (String key : specMap.keySet()) {//循环规格
                List<String> specList = (List<String>) specMap.get(key);//["天空之境","珠光贝母"]
                List<Map> newSpecList = new ArrayList<>();//新的集合 [{ 'option':'天空之境',checked:true },{ 'option':'珠光贝母',checked:false }]
                for (String value : specList) {
                    Map map = new HashMap();
                    map.put("option", value);//规格选项
                    if (skuSpecItems.get(key).equals(value)) {//如果和当年sku的规格相同，那就是选中
                        map.put("checked", true);//被选中
                    } else {
                        map.put("checked", false);//未选中
                    }

                    Map<String,Object> currentSpec=JSON.parseObject(sku.getSpec());//当前sku的spec
                    currentSpec.put(key,value);
                    String specJson=JSON.toJSONString(currentSpec,SerializerFeature.MapSortField);
                    map.put("url",skuUrlMap.get(specJson));

                    newSpecList.add(map);
                }
                specMap.put(key, newSpecList);//用新的集合替换原来的集合
            }
            dataModel.put("specMap", specMap);

            context.setVariables(dataModel);

            //2.准备文件，指定目标文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");

            //3.调用thymeleaf模板引擎生成静态页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
